<template>
  <div>
    <a-card
      class="eip-admin-card-small"
      :bordered="false"
      v-if="table.search.option.config.length > 0"
    >
      <eip-search
        :option="table.search.option"
        @search="search"
        @advanced="advanced"
      ></eip-search>
    </a-card>

    <a-card class="eip-admin-card-small" :loading="card.loading">
      <vxe-toolbar
        ref="runToolbar"
        custom
        print
        export
        :refresh="{ query: initData }"
      >
        <template v-slot:buttons>
          <a-space>
            <template v-for="(button, index) in buttons">
              <a-button
                v-if="button.type != 'upload'"
                :type="button.type"
                :key="index"
                @click="buttonClick(button)"
              >
                <a-icon :type="button.icon" :theme="button.theme" />
                {{ button.name }}</a-button
              >
              <a-upload
                v-if="button.type == 'upload'"
                :key="index"
                accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                :showUploadList="false"
                @change="uploadChange(button)"
                :customRequest="uploadCustomRequest"
              >
                <a-button type="primary">
                  <a-icon :type="button.icon" :theme="button.theme" />
                  {{ button.name }}
                </a-button></a-upload
              >
            </template>
          </a-space>
        </template>
      </vxe-toolbar>

      <a-spin :spinning="table.loading">
        <vxe-table
          ref="runTable"
          v-if="table.loaded"
          :border="agile.config.style.border"
          :column-config="{
            isCurrent: agile.config.style.columnIsCurrent,
            isHover: true,
          }"
          :row-config="{
            isCurrent: agile.config.style.rowIsCurrent,
            isHover: true,
            height: agile.config.style.rowHeight,
          }"
          :seq-config="{
            startIndex: (table.page.param.current - 1) * table.page.param.size,
          }"
          :stripe="agile.config.style.stripe"
          :print-config="{}"
          :export-config="{}"
          :height="table.height"
          :data="table.data"
          :tooltip-config="{ showAll: true }"
          @cell-dblclick="cellDbClick"
        >
          <vxe-table-column
            :type="agile.config.style.select"
            width="60"
            align="center"
          ></vxe-table-column>
          <vxe-table-column
            type="seq"
            title="序号"
            width="60"
          ></vxe-table-column>

          <vxe-table-column
            v-for="(item, i) in table.columns"
            :key="i"
            :field="item.field"
            :title="item.title"
            :width="item.width"
            :align="item.align"
            :sortable="item.sort"
            showOverflow="ellipsis"
          >
            <template v-slot="{ row }">
              <div v-if="item.style && item.style.length > 0">
                <template v-for="(items, index) in item.style">
                  <a-tag
                    :key="index"
                    :color="items.presets ? items.presets : items.custom"
                    v-if="items.value == row[item.field]"
                  >
                    {{ items.content }}
                  </a-tag>
                </template>
              </div>
              <template v-else>{{ row[item.field] }}</template>
            </template>
          </vxe-table-column>
        </vxe-table>

        <a-pagination
          class="padding-top-sm float-right"
          v-model="table.page.param.current"
          v-if="agile.config.style.paging"
          size="small"
          show-size-changer
          show-quick-jumper
          :page-size-options="table.page.sizeOptions"
          :show-total="(total) => `共 ${total} 条`"
          :page-size="table.page.param.size"
          :total="table.page.total"
          @change="initData"
          @showSizeChange="sizeChange"
        ></a-pagination>
      </a-spin>
    </a-card>

    <edit
      ref="edit"
      v-if="edit.visible"
      :visible.sync="edit.visible"
      :title="edit.title"
      :config="edit.config"
      :update="edit.update"
      :copy="edit.copy"
      :isWorkflow="edit.isWorkflow"
      :workflowData="workflowDo.data"
      @ok="perateStatus"
    ></edit>
  </div>
</template>

<script>
import { menubutton } from "@/services/common/usercontrol/toolbar";
import edit from "./edit";
import eipSearch from "@/pages/common/usercontrol/eip-search";
import eipToolbar from "@/pages/common/usercontrol/eip-toolbar";
import {
  query,
  queryConfig,
  del,
  eventApi,
  workflowEngineRevokeByCreateUser,
} from "@/services/system/agile/run/list";
import { request } from "@/utils/request";
import { selectTableRow, deleteConfirm } from "@/utils/util";
import XEUtils from "xe-utils";
export default {
  data() {
    return {
      api: eventApi, //api执行{param:'',url:''}

      //表格配置信息
      table: {
        page: {
          param: {
            current: 1,
            size: this.eipPage.size,
            sord: "desc",
            sidx: "",
            filters: "",
            type: 0,
            rote: {
              path: "",
            },
            configId: this.configId,
            menuId: this.menuId,
            haveDataPermission: false, //是否具有数据权限
            isPaging: true,
          },

          total: 0,
          sizeOptions: this.eipPage.sizeOptions,
        },

        height: this.eipHeaderHeight() - 140 + "px",
        loading: false,
        loaded: false, //配置是否加载完成
        data: [],
        search: {
          option: {
            labelCol: 8,
            wrapperCol: 16,
            num: 6,
            config: [],
          },
        },
        columns: [],
      },

      //敏捷开发配置信息
      agile: {
        configId: null, //配置Id
        config: {
          columns: [], //表格控件
          search: {
            labelCol: 8,
            wrapperCol: 16,
            num: 3, //显示个数
            columns: [], //查询条件
          },
          filter: [], //筛选条件
          button: [], //按钮
          style: {
            rowHeight: 40,
            paging: true,
            stripe: true,
            columnIsCurrent: true,
            rowIsCurrent: true,
            select: "checkbox",
            border: "full",
          },
          phone: {
            style: 1, //卡片模版
            title: undefined, //标题
            subTitle: undefined, //摘要
            columns: [], //显示字段
            cover: undefined, //封面
            coverPosition: undefined, //显示位置
            coverShowType: undefined, //显示方式
          },
        },
      },

      buttons: [], //按钮

      //编辑组件
      edit: {
        visible: false,
        title: null,
        copy: false,
        config: null, //编辑页面配置Id
        isWorkflow: false,
      },

      route: {
        name: this.name,
      },

      card: {
        loading: true,
      },

      //流程数据
      workflowDo: {
        data: {
          processId: this.menuId,
          processInstanceId: null,
          activityId: null,
          taskId: null,
          type: this.eipWorkflowDoType["审核"],
        },
      },
    };
  },
  props: {
    configId: {
      type: String,
    },
    menuId: {
      type: String,
    },

    name: {
      type: String,
    },

    havecard: {
      type: Boolean,
      default: false,
    }, //选项卡长度
  },
  components: { eipSearch, eipToolbar, edit },
  created() {
    const route = this.$route;
    if (!this.menuId) {
      this.route.name = route.name;
      this.table.page.param.menuId = route.meta.menuId;
      this.table.page.param.configId = route.meta.params.id;
    }

    this.initButton();
    this.initConfig();
  },
  methods: {
    /**
     * 按钮初始化
     */
    initButton() {
      let that = this;
      menubutton({
        menuId: this.table.page.param.menuId,
      }).then((result) => {
        if (result.code == that.eipResultCode.success) {
          that.buttons = result.data;
        }
      });
    },

    /**
     * 点击事件
     */
    buttonClick(item) {
      let that = this;
      that.edit.isWorkflow = false;
      switch (item.method) {
        case "add": //新增
          this.add();
          break;
        case "update": //编辑
          this.update();
          break;
        case "del": //删除
          this.del();
          break;
        case "copy": //复制
          this.copy();
          break;
        case "import": //导入数据
          break;
        case "importtemplate": //导入数据模板下载
          break;
        case "export": //导出数据模板下载
          break;
        case "workflowStart": //新增
          that.edit.isWorkflow = true;
          this.add();
          break;
        case "workflowRevoke": //新增
          this.workflowRevoke();
          break;
        default:
          //动态执行script
          eval(item.script);
          break;
      }
    },

    /**
     * 添加
     */
    add() {
      if (!this.edit.config) {
        this.$message.error("未配置编辑页面表单");
      } else {
        this.edit.update = null;
        this.edit.copy = false;
        this.edit.visible = true;
        this.edit.disabled = false;
        this.edit.title = "新增-" + this.route.name;
      }
    },

    /**
     * 编辑
     */
    update() {
      if (!this.edit.config) {
        this.$message.error("未配置编辑页面表单");
      } else {
        let that = this;
        selectTableRow(
          that.$refs.runTable,
          function (row) {
            that.edit.update = row;
            that.edit.disabled = false;
            that.edit.title = "编辑-" + that.route.name;
            that.edit.visible = true;
            that.edit.copy = false;
          },
          that
        );
      }
    },

    /**
     * 删除
     */
    del() {
      let that = this;
      selectTableRow(
        that.$refs.runTable,
        function (rows) {
          //提示是否删除
          deleteConfirm(
            that.eipMsg.delete,
            function () {
              that.$loading.show({ text: that.eipMsg.delloading });
              let ids = XEUtils.map(rows, (item) => item.RelationId);
              del({
                configId: that.agile.configId,
                id: ids.join(","),
              }).then((result) => {
                that.$loading.hide();
                if (result.code == that.eipResultCode.success) {
                  that.reload();
                  that.$message.success(result.msg);
                } else {
                  that.$message.error(result.msg);
                }
              });
            },
            that
          );
        },
        that,
        false
      );
    },

    /**
     * 复制
     */
    copy() {
      if (!this.edit.config) {
        this.$message.error("未配置编辑页面表单");
      } else {
        let that = this;
        selectTableRow(
          that.$refs.runTable,
          function (row) {
            that.edit.update = row;
            that.edit.disabled = false;
            that.edit.title = "复制-" + that.route.name;
            that.edit.visible = true;
            that.edit.copy = true;
          },
          that
        );
      }
    },

    /**
     * 双击事件
     */
    cellDbClick({
      row,
      rowIndex,
      $rowIndex,
      column,
      columnIndex,
      $columnIndex,
      $event,
    }) {
      this.edit.update = row;
      this.edit.title = "查看-" + that.route.name;
      this.edit.visible = true;
      this.edit.disabled = true;
      this.edit.copy = false;
    },
    /**
     * 查看
     */
    detail() {
      if (!this.edit.config) {
        this.$message.error("未配置编辑页面表单");
      } else {
        let that = this;
        selectTableRow(
          that.$refs.runTable,
          function (row) {
            that.edit.update = row;
            that.edit.disabled = true;
            that.edit.title = "查看-" + that.route.name;
            that.edit.visible = true;
            that.edit.copy = false;
          },
          that
        );
      }
    },
    /**
     * 列表初始化
     */
    search(filters) {
      this.table.page.param.current = 1;
      this.table.page.param.filters = filters;
      this.initData();
    },

    /**
     * 初始化配置
     */
    async initConfig() {
      let that = this;
      that.agile.configId = this.table.page.param.configId;
      that.agile.config.columns = [];
      that.table.loading = true;
      request(
        "/agile/" + that.agile.configId + ".txt?time=" + new Date().getTime(),
        {
          time: new Date().getTime(),
        }
      )
        .then(async function (result) {
          that.agile.config = JSON.parse(result.publicJson);
          await that.initSearch();
          that.initColumns();
          that.initData();
          that.card.loading = false;
          that.initConnect();
          that.table.loaded = true;
          that.initBaseConfig();
        })
        .catch(function (error) {
          that.$message.error("解析错误,请稍后重试");
        });
    },

    /**
     * 初始化配置信息
     */
    initBaseConfig() {
      let that = this;
      queryConfig({ configId: that.agile.configId, menuIdNull: false }).then(
        (result) => {
          if (result.code == that.eipResultCode.success) {
            that.edit.config = result.data[0];
          }
        }
      );
    },

    /**
     *
     */
    initConnect() {
      let that = this;
      setTimeout(function () {
        that.$refs.runTable.connect(that.$refs.runToolbar);
      }, 1000);
    },

    /**
     * 渲染列
     */
    initColumns() {
      let that = this;
      that.agile.config.columns.forEach((item) => {
        if (item.isShow) {
          var column = {
            field: item.name,
            title: item.description,
            align: item.align,
            sort: item.isSort,
            width: item.width,
            style: item.style,
          };
          that.table.columns.push(column);
        }
      });
    },

    /**
     * 初始化查询
     */
    async initSearch() {
      let that = this;
      if (that.agile.config.search) {
        if (that.agile.config.search.num) {
          that.table.search.option.num = that.agile.config.search.num;
        }
        if (that.agile.config.search.labelCol) {
          that.table.search.option.labelCol = that.agile.config.search.labelCol;
        }
        if (that.agile.config.search.wrapperCol) {
          that.table.search.option.wrapperCol =
            that.agile.config.search.wrapperCol;
        }
        let config = [];

        for (
          let index = 0;
          index < that.agile.config.search.columns.length;
          index++
        ) {
          const item = that.agile.config.search.columns[index];
          switch (item.type) {
            case "input":
              config.push({
                field: item.field,
                op: item.op,
                placeholder: item.placeholder,
                title: item.title,
                value: "",
                type: "text",
              });
              break;
            case "select":
              //得到具体配置
              var data = item.typeConfig;
              if (data) {
                switch (data.sourceType) {
                  case "dynamic":
                    //条件替换值
                    var conditions = data.sourceConfig.conditions.filter(
                      (f) => f.condition
                    );

                    var result = await businessDataFormSource({
                      table: data.sourceConfig.name,
                      key: data.sourceKey,
                      value: data.sourceValue,
                      filters: that.getWhereFilter(conditions),
                      sidx: data.sourceOrder, //排序字段
                      sord: data.sourceOrderType[0], //排序方式
                    });
                    if (result.code === that.eipResultCode.success) {
                      let dynamicData = [];
                      result.data.forEach((res) => {
                        dynamicData.push({
                          value: res[data.sourceValue],
                          key: res[data.sourceKey],
                        });
                      });

                      config.push({
                        field: item.field,
                        op: item.op,
                        placeholder: item.placeholder,
                        title: item.title,
                        type: "select",
                        source: {
                          type: "customer",
                          format: dynamicData,
                        },
                      });
                    }
                    break;
                  case "customer":
                    config.push({
                      field: item.field,
                      op: item.op,
                      placeholder: item.placeholder,
                      title: item.title,
                      type: "select",
                      source: {
                        type: "customer",
                        format: data.sourceCustomer,
                      },
                    });
                    break;
                }
              }

            default:
              break;
          }
        }
        that.table.search.option.config = config;
      }
    },

    /**
     * 初始化列表数据
     */
    initData() {
      let that = this;
      that.table.loading = true;
      that.table.page.param.isPaging = that.agile.config.style.paging;
      query(that.table.page.param).then(function (result) {
        if (result.code == that.eipResultCode.success) {
          let queryData = result.data;
          that.table.data = queryData.data;
          if (that.agile.config.style.paging) {
            that.table.page.total = queryData.count;
          }
        }
        that.table.loading = false;
      });
    },

    /**
     *数量改变
     */
    sizeChange(current, pageSize) {
      this.table.page.param.size = pageSize;
    },

    /**
     *导出
     */
    report() {},

    /**
     *提示状态信息
     */
    perateStatus(result) {
      if (result.code === this.eipResultCode.success) {
        this.reload();
      }
    },

    /**
     * 重新加载
     */
    reload() {
      this.table.page.param.current = 1;
      this.initData();
    },

    /**
     * 权限按钮加载完毕
     */
    toolbarOnload(buttons) {},

    /**
     * 调整,收起展开高度
     */
    advanced(advanced) {
      var height = this.havecard ? 200 : 160;
      if (advanced) {
        //判断具有几行
        var number =
          this.table.search.option.config.length / this.table.search.option.num;
        if (number % 1 === 0) {
          number += 1;
        } else {
          number = Math.ceil(number);
        }
        height = height + (number - 1) * 40;
      }

      this.table.height = this.eipHeaderHeight() - height;
    },

    /**
     * 悬浮显示
     */
    tooltip({ type, column, row, items, _columnIndex }) {
      const { property } = column;
      if (row) {
        return row[property];
      }
      return null;
    },

    /**
     * 取消
     */
    workflowRevoke() {
      let that = this;

      selectTableRow(
        that.$refs.runTable,
        function (rows) {
          //判断流程是否结束
          var result = true;
          rows.forEach((item, index) => {
            if (item.Status == 100) {
              that.$message.error("第" + (index + 1) + "行流程已结束");
              result = false;
              return false;
            }
            if (item.Status == 10) {
              that.$message.error("第" + (index + 1) + "行流程已撤销");
              result = false;
              return false;
            }
          });
          if (result) {
            that.$confirm({
              title: "操作提示?",
              content: "确定取消流程?",
              okText: "确定",
              okType: "danger",
              cancelText: "取消",
              onOk() {
                that.$message.loading("取消中");
                let ids = XEUtils.map(rows, (item) => item.RelationId);
                workflowEngineRevokeByCreateUser({
                  processInstanceId: ids.join(","),
                }).then((result) => {
                  that.$message.destroy();
                  if (result.code == that.eipResultCode.success) {
                    that.reload();
                    that.$message.success(result.msg);
                  } else {
                    that.$message.error(result.msg);
                  }
                });
              },
              onCancel() {},
            });
          }
        },
        that,
        false
      );
    },
  },
};
</script>

<style lang="less" scoped>
</style>
